/*
 * PDF cleaning tool: general purpose pdf syntax washer.
 *
 * Rewrite PDF with pretty printed objects.
 * Garbage collect unreachable objects.
 * Inflate compressed streams.
 * Create subset documents.
 *
 * TODO: linearize document for fast web view
 */

#include "mupdf/pdf.h"

static void usage(void)
{
	fprintf(stderr,
		"usage: mutool clean [options] input.pdf [output.pdf] [pages]\n"
		"\t-p -\tpassword\n"
		"\t-g\tgarbage collect unused objects\n"
		"\t-gg\tin addition to -g compact xref table\n"
		"\t-ggg\tin addition to -gg merge duplicate objects\n"
		"\t-s\tclean content streams\n"
		"\t-d\tdecompress all streams\n"
		"\t-l\tlinearize PDF\n"
		"\t-i\ttoggle decompression of image streams\n"
		"\t-f\ttoggle decompression of font streams\n"
		"\t-a\tascii hex encode binary streams\n"
		"\t-z\tdeflate uncompressed streams\n"
		"\tpages\tcomma separated list of page numbers and ranges\n"
		);
	exit(1);
}
typedef struct globals_s
{
	pdf_document* doc;
	fz_context* ctx;
} globals;
int main(int argc, char **argv)
{
	char *infile;
	char *outfile = "out.pdf";
	char *password = "";
	int c;
	fz_write_options opts = {0};
	int errors = 0;
	fz_context *ctx;
	opts.do_garbage = 3;
	opts.errors= &errors;
	opts.continue_on_error = 1;
	 
	

	ctx = fz_new_context(NULL, NULL, FZ_STORE_UNLIMITED);
	if (!ctx)
	{
		fprintf(stderr, "cannot initialise context\n");
		exit(1);
	}

	fz_try(ctx)
	{
		/*pdf_clean_file(ctx, "C:\\Code\\test.pdf", "C:\\Code\\testout.pdf", "", &opts, &argv[fz_optind], argc - fz_optind);*/



		globals glo = { 0 };

		glo.ctx = ctx;

		fz_try(ctx)
		{
			glo.doc = pdf_open_document(ctx, infile);
			if (pdf_needs_password(ctx, glo.doc))
				if (!pdf_authenticate_password(ctx, glo.doc, password))
					fz_throw(glo.ctx, FZ_ERROR_GENERIC, "cannot authenticate password: %s", infile);

		 

			pdf_write_document(ctx, glo.doc, outfile, &opts);
		}
		fz_always(ctx)
		{
			pdf_close_document(ctx, glo.doc);
		}
		fz_catch(ctx)
		{
			if (&opts && &opts->errors)
				&opts->errors = &opts->errors + 1;
		}

	}
	fz_catch(ctx)
	{
		errors++;
	}
	fz_drop_context(ctx);

	return errors != 0;
}
